import React, { useEffect, useState } from 'react';
import { Table, Button, Modal, message, Tabs, Space, Tag } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';
import { observer } from 'mobx-react-lite';
import { modelStore } from './store/modelStore';
import ModelForm from './ModelForm';
import { Model } from './store/modelTypes';

const { TabPane } = Tabs;

export type ModelType = 'all' | 'chat' | 'embedding' | 'reRanking';

const ModelList: React.FC = observer(() => {
  const [activeTab, setActiveTab] = useState<ModelType>('all');
  const [viewType, seViewType] = useState<'create' | 'edit' | 'view'>('create');

  useEffect(() => {
    modelStore.fetchModels();
  }, []);

  const handleCreate = () => {
    seViewType('create');
    modelStore.showCreateModal();
  };

  const handleEdit = (model: Model) => {
    seViewType('edit');
    modelStore.showEditModal(model);
  };

  const handleView = (model: Model) => {
    seViewType('view');
    modelStore.showEditModal(model);
  };

  const handleDelete = async (id: string) => {
    try {
      await modelStore.deleteModel(id);
      message.success('删除成功');
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleModalOk = async (values: any) => {
    try {
      await modelStore.saveModel(values);
      message.success('保存成功');
    } catch (error) {
      message.error('保存失败');
    }
  };

  const getFilteredModels = () => {
    if (activeTab === 'all') {
      return modelStore.models || [];
    }
    return (modelStore.models || []).filter(model => model.modelType === activeTab);
  };

  const getModelTypeTag = (type: string) => {
    const typeMap = {
      chat: { color: 'blue', text: '大语言模型' },
      embedding: { color: 'green', text: '向量模型' },
      reRanking: { color: 'purple', text: '重排序模型' }
    };
    const config = typeMap[type as keyof typeof typeMap];
    return config ? <Tag color={config.color}>{config.text}</Tag> : null;
  };


  const getChatTypeTag = (type: string) => {
    const typeMap = {
      openai_gpt: { color: 'purple', text: 'GPT' },
      claude: { color: 'purple', text: 'Claude' },
      qwen: { color: 'green', text: 'Qwen' },
      wenxinyiyan: { color: 'green', text: '文心一言' },
      xinghuo: { color: 'green', text: '星火' },
      deepseek: { color: 'green', text: 'Deepseek' },
      doubao: { color: 'green', text: '字节跳动' },
      ollama: { color: 'yellow', text: 'ollama' },
      llm: { color: 'yellow', text: 'vllm' },
      custom: { color: 'gray', text: '自定义' }
    };
    const config = typeMap[type as keyof typeof typeMap];
    return config ? <Tag color={config.color}>{config.text}</Tag> : null;
  };

    const getStatusTag = (type: string) => {
    const typeMap = {
      active: { color: 'green', text: '活跃' },
      inactive: { color: 'yellow', text: '未激活' },
      deprecated: { color: 'gray', text: '已弃用' },
      maintenance: { color: 'purple', text: '维护中' },
    };
    const config = typeMap[type as keyof typeof typeMap];
    return config ? <Tag color={config.color}>{config.text}</Tag> : null;
  };

  const columns = [
  {
    title: '模型名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '模型标识',
    dataIndex: 'mark',
    key: 'mark',
  },
  {
    title: '模型分类',
    dataIndex: 'modelType',
    key: 'modelType',
    render: (type: string) => getModelTypeTag(type),
  },
  {
    title: '对接方式',
    dataIndex: 'connectionType',
    key: 'connectionType',
    render: (type: string) => (
      <Tag color={type === 'standard' ? 'blue' : 'orange'}>
        {type === 'standard' ? '标准' : '自定义'}
      </Tag>
    ),
  },
  {
    title: '系统模型',
    dataIndex: 'isSystem',
    key: 'isSystem',
    render: (isSystem: boolean) => (
      <Tag color={isSystem ? 'red' : 'green'}>
        {isSystem ? '是' : '否'}
      </Tag>
    ),
  },
    {
      title: '模型类型',
      dataIndex: 'chatType',
      key: 'chatType',
      render: (type: string) => getChatTypeTag(type),
    },
    {
      title: '模型状态',
      dataIndex: 'status',
      key: 'status',
    render: (type: string) => getStatusTag(type),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Model) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handleView(record)}
          >
            查看
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            // disabled={true}
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    }
  ];

  return (
    <div style={{ 
      display: 'flex', 
      flexDirection: 'column', 
      height: '100%',
      overflow: 'hidden'
    }}>
      {/* 固定顶部区域 */}
      <div style={{ 
        padding: '16px 24px',
        background: '#fff',
        borderBottom: '1px solid #f0f0f0',
        zIndex: 1
      }}>
        <Tabs
          activeKey={activeTab}
          onChange={(key) => setActiveTab(key as ModelType)}
          style={{ marginBottom: 16 }}
        >
          <TabPane tab="全部模型" key="all" />
          <TabPane tab="大语言模型" key="chat" />
          <TabPane tab="向量模型" key="embedding" />
          <TabPane tab="重排序模型" key="reRanking" />
        </Tabs>

        <div style={{ marginBottom: 16 }}>
          <Button type="primary" onClick={handleCreate}>
            创建模型
          </Button>
        </div>
      </div>

      {/* 可滚动的内容区域 */}
      <div style={{ 
        flex: 1, 
        overflow: 'auto',
        padding: '0 24px',
        background: '#fff'
      }}>
        <Table
          columns={columns}
          dataSource={getFilteredModels()}
          rowKey="id"
          loading={modelStore.loading}
          // scroll={{ y: 'calc(100vh - 250px)' }}
          locale={{ emptyText: '暂无数据' }}
        />
      </div>

      <Modal
      title={
          viewType === 'create'
            ? '新建模型'
            : viewType === 'edit'
            ? '编辑模型'
            : '查看模型'
        }
        open={modelStore.modalVisible}
        onCancel={modelStore.hideModal}
        footer={null}
        width={800}
        destroyOnClose
        bodyStyle={{
          maxHeight: 'calc(100vh - 200px)',
          overflow: 'auto',
          padding: '24px'
        }}
      >
        <ModelForm
          initialValues={modelStore.editingModel}
          defaultType={activeTab === 'all' ? undefined : activeTab}
          type={viewType}
          onSubmit={handleModalOk}
          onCancel={modelStore.hideModal}
        />
      </Modal>
    </div>
  );
});

export default ModelList;